package com.dragon.app.marvel.core;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dragon.app.marvel2.NewMarvelCoreService;
import com.dragon.app.um.vo.JsonResult;
import com.dragon.loan.entity.AcLoanApplyInfo;
import com.dragon.loan.service.LoanInfoIDragonService;
import com.dragon.rabbitmq.CoreServiceProduct;
import com.fintech.common.constant.ErrorCode;
import com.fintech.common.util.HttpClientUtils;
import com.fintech.common.vo.FintechResult;
import com.marvels.common.utils.MarvelsLogUtil;

/**
 * 新核心系统跟老核心系统的对接扭转服务类
 * @author shan
 *
 */
@Service("newMarvelCoreService")
public class NewMarvelCoreServiceImpl implements NewMarvelCoreService{
	private final static String NEW_MARVEL_ON = "ON";
	private final static String NEW_MARVEL_CODE_SUCCESS = "success";
	private final static String NEW_MARVEL_CODE_ERROR = "error";
	private final static String NEW_MARVEL_CODE_FAIL = "fail";
	private final static String MATCH_FAIL = "-99";
	/** 是否进入新核心   0  否   1 是 */
	private final static Byte GO_NEW_MARVELS = new Byte("1");
	
	@Autowired
	private LoanInfoIDragonService loanInfoIDragonService;
	@Autowired
	private CoreServiceProduct coreServiceProduct;
	@Value("${new_marvel_start}")
	private String marvelStart;
	
	@Value("${new_marvel_base_url}")
	private String newMarvelBaseUrl;
	
	/**
	 * 新核心系统是否打开的一个开关
	 * @param  idCard 身份证号  如果传null的话 则只判断new_marvel_start 
	 * @param  loanId 贷款单号  
	 * @return  true 走新核心逻辑  false走旧核心逻辑
	 * @author laijingshan
	 * @date 2018年9月20日
	 */
	@Override
	public boolean isMarvelStart(String idCard, String loanId){
		MarvelsLogUtil.getInstance().info("===============isMarvelStart===========marvelStart" + marvelStart);
		if(StringUtils.isEmpty(loanId) 
				&& StringUtils.isEmpty(idCard)){
			return StringUtils.equalsIgnoreCase(marvelStart, NEW_MARVEL_ON);
			
		}else if(StringUtils.isEmpty(loanId)){
			loanId = loanInfoIDragonService.selectCustApplyingLoanId(idCard);
		}
		// loanId 为空
		if(StringUtils.isEmpty(loanId)){
			return StringUtils.equalsIgnoreCase(marvelStart, NEW_MARVEL_ON);
		}
		
		// 如果loanId 不等于空
		AcLoanApplyInfo loan = loanInfoIDragonService.queryLoanBasicInfo(loanId);
		if(loan == null){
			return StringUtils.equalsIgnoreCase(marvelStart, NEW_MARVEL_ON);
		}
		Byte goNewMarvels = loan.getGoNewMarvels();
		boolean result = StringUtils.equalsIgnoreCase(marvelStart, NEW_MARVEL_ON)
								&& GO_NEW_MARVELS.equals(goNewMarvels);
		MarvelsLogUtil.getInstance().info("===============isMarvelStart===========result" + result + "loanId = " + loanId + "goNewMarvels" + goNewMarvels);
		return result;
		
	}
	
	/**
	 * 发送post请求
	 * @param url   		发送请求的url
	 * @param param 		这个会格式化成json串作为请求体发送
	 * @param resultClass	JsonResult 这个的泛型类型
	 * @return
	 * @author laijingshan
	 * @date 2018年9月20日
	 */
	@Override
	public <T>JsonResult<T> getForObjectPost(String url, Object param, Class<T> resultClass){
		url = newMarvelBaseUrl + url;
		MarvelsLogUtil.getInstance().info("=================getForObjectPost====================url = " + url + " and param = " + JSON.toJSONString(param) + " and resultClass = " + JSON.toJSONString(resultClass));
		JsonResult<T> jsonResult = new JsonResult<T>();
		String result = HttpClientUtils.sendHttpPost(url, JSON.toJSONString(param));
		MarvelsLogUtil.getInstance().info("=================getForObjectPost====================result = " + result + url);
		if(StringUtils.isEmpty(result)){
			jsonResult.setErrorMsg("服务器开了小差");
			return jsonResult;
		}
		JSONObject resultJsonObj = JSON.parseObject(result);
		String code = resultJsonObj.getString("code");
		String message = resultJsonObj.getString("message");
		
		if(NEW_MARVEL_CODE_SUCCESS.equals(code)){
			try {
				T data = resultJsonObj.getObject("data", resultClass);
				jsonResult.setData(data);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("====================getForObjectPost转换异常===================" + result);
				try {
					T newInstance = resultClass.newInstance();
					jsonResult.setData(newInstance);
				} catch (InstantiationException | IllegalAccessException e1) {
					e1.printStackTrace();
				}
			}
		}
		
		// code 需要做下映射 
		code = getCodeMapper(code);
		jsonResult.setErrorCode(code);
		jsonResult.setMessage(message);
		return jsonResult;
	}
	
	public static void main(String[] args) {
		String result = HttpClientUtils.sendHttpPost("http://10.0.17.30/financial/process/api/repaymentNoMobile", "{\"loanId\":\"18092720435199200\",\"payType\":\"A005\",\"planCode\":\"FEc10397d854104b21a7f093357e96710c\"}");
		System.out.println(result + "");
	}
	
	/**
	 * 发送post请求
	 * @param url   		发送请求的url
	 * @param param 		这个会格式化成json串作为请求体发送
	 * @param resultClass	JsonResult 这个的泛型类型
	 * @return
	 * @author laijingshan
	 * @date 2018年9月20日
	 */
	@Override
	public FintechResult getForObjectPost(String url, Object param){
		url = newMarvelBaseUrl + url;
		MarvelsLogUtil.getInstance().info("=================getForObjectPost====================url = " + url + " and param = " + JSON.toJSONString(param));
		String result =null;
		if(param!=null){
			result= HttpClientUtils.sendHttpPost(url, JSON.toJSONString(param));
		}else{
			result= HttpClientUtils.sendHttpPost(url);
		}
		if(StringUtils.isEmpty(result)){
			FintechResult.getResult(ErrorCode.FAIL, "服务器开了小差", null);
		}
		MarvelsLogUtil.getInstance().info("=================getForObjectPost====================result = " + result);
		JSONObject resultJsonObj = JSON.parseObject(result);
		String code = resultJsonObj.getString("code");
		String message = resultJsonObj.getString("message");
		Object data = resultJsonObj.get("data");
		// code 需要做下映射 
		code = getCodeMapper(code);
		return FintechResult.getResult(code, message, data);
	}
	
	
	/**
	 * 发送post请求
	 * @param url   		发送请求的url
	 * @param param 		这个会格式化成json串作为请求体发送
	 * @param resultClass	JsonResult 这个的泛型类型
	 * @return
	 * @author laijingshan
	 * @date 2018年9月20日
	 */
	@Override
	public <T>com.dragon.app.commons.vo.JsonResult<T> getForObjectPostRepayment(String url, Object param, Class<T> resultClass){
		JsonResult<T> forObjectPostRepayment = getForObjectPost(url, param, resultClass);
		com.dragon.app.commons.vo.JsonResult<T> jsonResult = new com.dragon.app.commons.vo.JsonResult<T>();
		jsonResult.setErrorCode(Integer.parseInt(forObjectPostRepayment.getErrorCode()));
		jsonResult.setMessage(forObjectPostRepayment.getMessage());
		jsonResult.setData(forObjectPostRepayment.getData());
		return jsonResult;
	}
	
	/**
	 * 根据新核心的code 返回老核心的code
	 * @param newMarvelCode 新核心的code
	 * @return
	 * @author laijingshan
	 * @date 2018年9月20日
	 */
	@Override
	public String getCodeMapper(String newMarvelCode){
		if(StringUtils.equalsIgnoreCase(newMarvelCode, NEW_MARVEL_CODE_SUCCESS)){
			return ErrorCode.SUCCESS;
		}else if(StringUtils.equalsIgnoreCase(newMarvelCode, NEW_MARVEL_CODE_ERROR)){
			return ErrorCode.EXCEPTION;
		}else if(StringUtils.equalsIgnoreCase(newMarvelCode, NEW_MARVEL_CODE_FAIL)){
			return ErrorCode.FAIL;
		}
		return newMarvelCode;
	}
	
	/**
	 * 发送到新核心 （整合版本由于前段响应问题需要使用异步执行 AsyncCallApi）
	 * @param loanId 贷款单号  发送到新核心
	 * @return
	 * @author laijingshan
	 * @date 2018年9月27日
	 */
	@Deprecated
	@Override
	public void sendLoanApplyMessage(String loanId){
		try {
			if(isMarvelStart(null, loanId)){
				coreServiceProduct.sendLoanApplyMessage(loanId);
				AcLoanApplyInfo acLoanApplyInfo = new AcLoanApplyInfo();
				acLoanApplyInfo.setLoanId(loanId);
				acLoanApplyInfo.setGoNewMarvels(new Byte("1"));
				loanInfoIDragonService.input(acLoanApplyInfo);
				MarvelsLogUtil.getInstance().info("=======sendLoanApplyMessage=======" + loanId);
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=======sendLoanApplyMessage=======" + loanId, e);
		}
	}
}
